package net.rock.utils;

import lombok.extern.slf4j.Slf4j;
import net.rock.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AdminSessionHolder {

    @Autowired
    private RestTemplate restTemplate;

    private String sessionId;

    public AdminSessionHolder() {
    }

    public String getSessionId() {
        if (StringUtils.isEmpty(sessionId)) {
            initSession();
        }
        return sessionId;
    }

    public void refresh() {
        releaseSession();
        initSession();
    }

    public void initSession() {
        User root = new User();
        root.setId(1);
        root.setUsername("root");
        root.setPassword("e10adc3949ba59abbe56e057f20f883e");
        root.setPermission(1);

        String sessionId = restTemplate.postForObject("http://userservice/api/account/login", root, String.class);
        if (StringUtils.isNotEmpty(sessionId)) {
            log.info("Logged in. Session ID: {}", sessionId);
            this.sessionId = sessionId;
        } else {
            throw new RuntimeException("Cannot login.");
        }
    }

    public void releaseSession() {
        if (StringUtils.isNotEmpty(sessionId)) {
            HttpHeaders requestHeaders = new HttpHeaders();
            List<String> cookies = new ArrayList<>();
            cookies.add("sessionID=" + sessionId);
            requestHeaders.put(HttpHeaders.COOKIE, cookies);
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);

            ResponseEntity<String> res = restTemplate.exchange(
                    "http://userservice/api/account/logout",
                    HttpMethod.GET,
                    requestEntity,
                    String.class
            );
            if (!res.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("Log out failed.");
            } else {
                log.info("Logged out.");
            }
        }
    }
}